package com.songtech.server.frame.chain;

import com.songtech.server.frame.chain.handler.BaseChainHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * Create By YINN on 2018/4/27 9:37
 * Description : 处理链管理器
 */
public class ChainManager {

    private List<BaseChainHandler> chain;   //处理链

    /**
     * Created by YINN on 2018/4/27 10:40.
     * @Description : 将处理器添加至处理链末尾
     * @Result : this
     */
    public ChainManager addLast(BaseChainHandler handler) {

        if (chain == null) {

            chain = new ArrayList<>();

        }

        chain.add(handler);

        return this;
    }

    /**
     * Created by YINN on 2018/4/27 10:40.
     * @Description : 将处理器添加至处理链首位
     * @Result : this
     */
    public ChainManager addBefore(BaseChainHandler handler) {

        if (chain == null) {

            chain = new ArrayList<>();

        }

        chain.add(0, handler);

        return this;
    }

    /**
     * Created by YINN on 2018/4/27 10:40.
     * @Description : 将处理器添加至处理链index位置,若index越界，则添加至处理链末尾
     * @Result : this
     */
    public ChainManager addAnyPosition(BaseChainHandler handler, int index) {

        if (chain == null) {

            chain = new ArrayList<>();

        }

        if (index - 1 > chain.size()) {

            chain.add(index, handler);

        } else {

            this.addLast(handler);

        }


        return this;
    }


    /**
     * Created by YINN on 2018/4/27 10:40.
     * @Description : 移除某个处理器
     * @Result : this
     */
    public ChainManager remove(BaseChainHandler handler) {

        if (chain != null && chain.contains(handler)) {

            chain.remove(handler);

        }

        return this;
    }


    /**
     * Created by YINN on 2018/4/27 10:40.
     * @Description : 移除第index个处理器
     * @Result : this
     */
    public ChainManager remove(int index) {

        if (chain != null && chain.size() - 1 > index) {

            chain.remove(index);

        }

        return this;
    }

    /**
     * Created by YINN on 2018/4/27 10:40.
     * @Description : 触发所有处理连中所有处理器
     * @Result :
     */
    public void trigger() {

        int len = chain.size();

        if (len > 0) {

            for (int i = 0; i < len; i++) {

                chain.get(i).exec();

            }

        }

    }

    /**
     * Created by YINN on 2018/4/27 10:42.
     * @param index : 游标
     * @Description : 触发第index个处理器
     * @Result :
     */
    public void triggerSingle(int index) {

        chain.get(index).exec();

    }


    /**
     * Created by YINN on 2018/4/27 10:42.
     * @Description : 清空处理链
     * @Result :
     */
    public void clear() {

        if (chain != null)
            chain.clear();

    }
}
